package com.book.config;


import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;


@Slf4j
@WebFilter(urlPatterns="/*")
public class WebRequestFilter implements Filter {

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        // 跳过健康检查
        if ("/actuator/health".equals(requestURI)){
            return;
        }
        MDC.put("traceId", UUID.randomUUID().toString());
        long t1 = System.currentTimeMillis();
        chain.doFilter(request,response);
        long t2 = System.currentTimeMillis();
        log.info("request:{},finished with:{}ms" , requestURI, (t2-t1) );
    }

}